package com.oracle.dao;

import com.oracle.dao.impl.OrdersDao;
import com.oracle.mapper.OrdersMapper;
import com.oracle.pojo.Orders;
import com.oracle.pojo.OrdersExample;
import com.oracle.pojo.vo.OrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Repository
public class OrderDaoImpl implements OrdersDao {

    @Autowired
    private OrdersMapper ordersMapper;

    @Override
    public List<Orders> selectOrders(OrderVo orderVo) {
        OrdersExample ordersExample = new OrdersExample();
        OrdersExample.Criteria criteria = ordersExample.createCriteria();
        if (orderVo.getOid()!=null&&orderVo.getOid()!=0){
            criteria.andOidEqualTo(orderVo.getOid());
        }
        if (orderVo.getStartOrderDate()!=null){
            criteria.andOrderdateGreaterThanOrEqualTo(orderVo.getStartOrderDate());
        }
        if (orderVo.getEndOrderDate()!=null){
            criteria.andOrderdateLessThanOrEqualTo(orderVo.getEndOrderDate());
        }
        if (orderVo.getMinPrice()!=null){
            criteria.andTotalGreaterThanOrEqualTo(orderVo.getMinPrice());
        }
        if (orderVo.getMaxPrice()!=null){
            criteria.andTotalLessThanOrEqualTo(orderVo.getMaxPrice());
        }
        List<Orders> list = ordersMapper.selectOrdresAllByExample(ordersExample);
        return list;
    }

    @Override
    public List<Orders> findSomeByUid(Integer uid) {
        OrdersExample ordersExample = new OrdersExample();
        OrdersExample.Criteria criteria = ordersExample.createCriteria();
        criteria.andUidEqualTo(uid);
        List<Orders> list = ordersMapper.selectByExample(ordersExample);
        if (list.isEmpty()){
            return null;
        }
        return list;
    }

    @Transactional
    @Override
    public Orders addNewOrder(BigDecimal total, Date date, Integer uid) {
        Orders orders = new Orders();
        orders.setUid(uid);
        orders.setTotal(total);
        orders.setOrderdate(date);
        orders.setPaycode(0);
        int i = ordersMapper.insertSelective(orders);
        if (i>0){
            i = ordersMapper.selectLastInsertId();
            orders.setOid(i);
            return orders;
        }
        return null;
    }

    @Override
    public Integer deleteOrdersByOid(Integer oid) {
        if (ordersMapper.deleteByPrimaryKey(oid)>0){
            return 200;
        }
        return 400;
    }

    @Override
    public Integer selectPayCodeByOid(Integer oid) {
        return ordersMapper.selectPayCodeByOid(oid);
    }

    @Override
    public Integer updateOrdersPayCodeByOid(int oid) {
        Integer integer = ordersMapper.updateOrdersPayCodeByOid(oid);
        while (integer>0){
            return 200;
        }
        return 400;
    }
}
